<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/12/24
 * Time: 10:58
 */

defined('BASEPATH') OR exit('No direct script access allowed');

class GoodsSku extends Admin_Controller
{
    public function index()
    {

        $this->load->model('goods_sku_model');
        $this->load->model('order_goods_model');
        $this->load->model('shelves_model');

        $this->load->library('pagination');
        $assoc = $this->uri->uri_to_assoc();

        $_param_option = array(
            'sku_name' => array(
                'col' => 'col-lg-4',
                'type' => 'text',
                'placeholder' => '输入产品名称、货号'
            )
        );

        $_param = array(
            'sku_name' => $this->input->get('sku_name'),
            'sl_title' => $this->input->get('sl_title'),
            'page' => $assoc['page'] > 0 ? intval($assoc['page']) - 1 : 0
        );

        $config['base_url'] = base_url('GoodsSku/') . 'index/page/';
        $config['total_rows'] = $this->goods_sku_model->sku_num($_param);
        $config['num_links'] = 6;
        $config['per_page'] = $this->goods_sku_model->limit_rows;
        $config['use_page_numbers']=true;
        $this->pagination->initialize($config);

        $shelves_list = $this->shelves_model->shelves_list(array('is_del = 0'), 1);

        $_sku_list = $this->goods_sku_model->sku_list($_param);

        $_3_day = strtotime('-3 day');
        $_5_day = strtotime('-5 day');
        $_10_day = strtotime('-10 day');

        foreach ($_sku_list as $k => $item) {
            $_sku_list[$k]['3_day'] = intval($this->order_goods_model->sku_goods_num($item['sku_num_sn'], array('start' => $_3_day)));
            $_sku_list[$k]['5_day'] = intval($this->order_goods_model->sku_goods_num($item['sku_num_sn'], array('start' => $_5_day)));
            $_sku_list[$k]['10_day'] = intval($this->order_goods_model->sku_goods_num($item['sku_num_sn'], array('start' => $_10_day)));
            $_sku_list[$k]['count'] = intval($this->order_goods_model->sku_goods_num($item['sku_num_sn']));
        }

        $data = array(
            'sku_list' => $_sku_list,
            'pages' => $this->pagination->create_links(),
            'param_option' => $_param_option,
            'shelves_list' => $shelves_list,
            'param' => $_param
        );

        $this->load->view('sku_list', $data);
    }

    public function shelves_list() {

        $this->load->model('shelves_model');

        $_param_option = array(
            'sku_name' => array(
                'col' => 'col-lg-4',
                'type' => 'text',
                'placeholder' => '输入产品名称、货号'
            )
        );

        $shelves_list = $this->shelves_model->shelves_list();

        $_action_link = array(
            array('href' => base_url('GoodsSku/shelves_set'), 'name' => '添加货架位'),
            array('href' => base_url('GoodsSku/shelves_batch_set'), 'name' => '批量上传')
        );

        $data = array(
            'shelves_list' => $shelves_list,
            'param_option' => $_param_option,
            'action_link' => $_action_link
        );

        $this->load->view('shelves_list', $data);
    }

    public function shelves_batch_set()
    {
        $this->load->library('excel');
        $this->load->model('shelves_model');
        $this->config->load('shelves_location');

        $list = $this->config->item('list');
        $level = $this->config->item('level');
        $loca = $this->config->item('loca');

        $config = array(
            'upload_path' => './album/',
            'allowed_types' => 'csv|xls',
            'max_size' => '1000000000'
        );

        $this->load->library('upload', $config);

        if ($this->upload->do_upload('fileUpload')) {

            $data = array('upload_data' => $this->upload->data());

            $shelves_data = $this->excel->ReadCsv($data['upload_data']['full_path']);

            if ($shelves_data) {

                unset($shelves_data[0]);

                foreach ($shelves_data as $row) {

                    $sl_title = trim($row[0]);

                    $arr_sl_title = explode('-', $sl_title);

                    $data = array(
                        'sl_title' => $sl_title,
                        'list_shelves' => $arr_sl_title[0],
                        'level_shelves' => $arr_sl_title[1],
                        'loca_shelves' => $arr_sl_title[2],
                        'is_del' => 0
                    );



                    $shelves_info = $this->shelves_model->shelves_info(array('sl_title' => $data['sl_title']));

                    if ($shelves_info['is_del'] === 0) {
                        continue;
                    }

                    if ($shelves_info) {
                        $this->shelves_model->shelves_update(array(
                            'is_del' => 0
                        ), $shelves_info['sl_id']);
                    } else {
                        $this->shelves_model->shelves_insert($data);
                    }
                }


            }
        }


        $this->load->view('shelves_batch_set');

    }

    public function shelves_set() {

        $this->config->load('shelves_location');
        $this->load->library('sys_message');
        $this->load->model('shelves_model');

        $list = $this->config->item('list');
        $level = $this->config->item('level');
        $loca = $this->config->item('loca');

        if ($_POST) {
            $she_li_id = intval($this->input->post('she_li_id'));
            $she_le_id = intval($this->input->post('she_le_id'));
            $she_loc_id = intval($this->input->post('she_loc_id'));

            !$list[$she_li_id]&& $this->sys_message->wrong('请选择排!');
            !$level[$she_le_id] && $this->sys_message->wrong('请选择层!');
            !$loca[$she_loc_id] && $this->sys_message->wrong('请选择位置!');

            $data = array(
                'sl_title' => "{$list[$she_li_id]}-{$level[$she_le_id]}-{$loca[$she_loc_id]}",
                'list_shelves' => $she_li_id,
                'level_shelves' => $she_le_id,
                'loca_shelves' => $she_loc_id
            );

            $shelves_info = $this->shelves_model->shelves_info(array('sl_title' => $data['sl_title']));

            $shelves_info['is_del'] === 0 && $this->sys_message->wrong('已经存在货架!');

            if ($shelves_info) {
                $this->shelves_model->shelves_update(array(
                    'is_del' => 0
                ), $shelves_info['sl_id']);
            } else {
                $this->shelves_model->shelves_insert($data);
            }


        }

        $data = array(
            'list' => $list,
            'level' => $level,
            'loca' => $loca
        );

        $this->load->view('shelves_set', $data);
    }

    public function shelves_del()
    {
        $this->load->model('shelves_model');
        $this->load->library('sys_message');

        $assoc = $this->uri->uri_to_assoc();

        $sl_id = intval($assoc['sl_id']);

        $sl_info = $this->shelves_model->shelves_info(array('sl_id' => $sl_id));

        !$sl_info && $this->sys_message->wrong('货架位不存在!');

        $this->shelves_model->shelves_del($sl_id);

        $this->sys_message->success('成功!');
    }

    public function sku_add_sl()
    {

        $this->load->model('shelves_model');
        $this->load->library('sys_message');

        $sl_title = $this->input->post('shelves_id');
        $sku_id = $this->input->post('sku_id');

        $shelves_id = $this->shelves_model->get_shelves_id($sl_title);

        $data = array(
            'sku_id' => $sku_id,
            'sl_id' => $shelves_id,
            'sl_title' => $sl_title,
            'add_time' => time()
        );

        !$shelves_id && $this->sys_message->wrong('货架不存在!');
        !$sku_id && $this->sys_message->wrong('SKU不存在!');

        $shelves_sku_info = $this->shelves_model->shelves_sku_info(array(
            'sl_id' => $data['sl_id'],
            'is_del' => 0
        ));

        $shelves_sku_info && $this->sys_message->wrong('货架已经被占用!');

        $this->shelves_model->set_shelves_sku($data);


        $this->sys_message->success('成功!');
    }

    public function print_code()
    {

        $this->load->model('goods_sku_model');
        $this->load->library('tcpdf_api');

        $assoc = $this->uri->uri_to_assoc();

        $sl_title = trim($assoc['sl_title']);

        $this->tcpdf_api->label_text($sl_title, 1);
    }

    public function correct_sku_number()
    {
        $this->load->model('goods_sku_model');
        $this->load->library('sys_message');

        $assoc = $this->uri->uri_to_assoc();

        $sku_id = intval($assoc['sku_id']);
        $sku_number = intval($this->input->post('sku_number'));
        $log_info = htmlspecialchars(trim($this->input->post('log_info')));

        !$sku_id && !$sku_number && $this->sys_message->wrong('参数错误!');

        $this->goods_sku_model->take_sku($sku_id, 2, $sku_number, 0, $log_info ? $log_info : '库存校正');

        $this->sys_message->success('修改库存成功!');

    }

    public function batch_up_goods_sku()
    {

        $this->load->library('excel');
        $this->load->model('shelves_model');
        $this->load->model('goods_sku_model');
        $this->config->load('shelves_location');

        $config = array(
            'upload_path' => './album/',
            'allowed_types' => 'csv|xls',
            'max_size' => '1000000000'
        );

        $this->load->library('upload', $config);

        if ($this->upload->do_upload('fileUpload')) {

            $data = array('upload_data' => $this->upload->data());

            $shelves_data = $this->excel->ReadCsv($data['upload_data']['full_path']);

            if ($shelves_data) {

                unset($shelves_data[0]);

                foreach ($shelves_data as $row) {
                    $sku_sn = $row[0];
                    $sel = $row[1];
                    $number = $row[2];

                    $goods_sku = $this->goods_sku_model->sku_info("upper(gs.sku_sn) = upper('{$sku_sn}')");
                    if ($goods_sku) {



                        $shelves_data = $this->goods_sku_model->shelves_info(array('sl_title' => $sel));

                        $this->goods_sku_model->up_sku_info(array(
                            'sl_title' => $sel,
                            'sl_id' => $shelves_data['sl_id'],
                            'sku_number' => $number
                        ), $goods_sku['sku_id']);
                    }
                }
            }
        }

        $this->load->view('batch_up_goods_sku');
    }

    public function fp_order() {
        $this->load->model('goods_sku_model');
        $this->load->model('order_model');
        $this->load->model('order_goods_model');
        $this->load->model('purchase_goods_model');
        $this->load->library('sys_message');

        $goods_list = $this->goods_sku_model->goods_fp();

        foreach ($goods_list as $row) {
            $sku_id = $row['sku_id'];

            $goods_sku = $this->goods_sku_model->sku_info(array('sku_id' => $sku_id));


            $data = array(
                'sku_id' => $sku_id,
                'storage_number' => $goods_sku['sku_number']
            );

            $order_number_arr = $this->order_goods_model->allot_pg_number($data);

            if ($order_number_arr['occupy_number'] > 0) {

                foreach ($order_number_arr['rec_ids'] as $rec_id => $row) {
                    $log_info = "<br /> #{$rec_id} 订单产品占用 <b style='color: #ab2134'>{$row['need_number']}</b> 个库存";

                    $purchase = $this->purchase_goods_model->subtract_order_purchase_number($rec_id, $row['need_number']);
                    $log_info .= $purchase ? "<br /> 取消 #{$purchase['pg_id']} 采购产品 <b style='color: #ab2134'>{$purchase['number']}</b> 个采购"  : '';

                    $this->order_model->check_orders($row['order_id'], 2, $log_info);
                }

                $this->goods_sku_model->take_sku($data['sku_id'], 2, 0, $order_number_arr['occupy_number'], "库存重新分配至订单");
            } else {
            }
        }
    }


    public function check_order_need_sku($_sku_id = 0)
    {
        $this->load->model('goods_sku_model');
        $this->load->model('order_model');
        $this->load->model('order_goods_model');
        $this->load->model('purchase_goods_model');
        $this->load->library('sys_message');

        $assoc = $this->uri->uri_to_assoc();

        $sku_id = $_sku_id ? $_sku_id : intval($assoc['sku_id']);

        $goods_sku = $this->goods_sku_model->sku_info(array('sku_id' => $sku_id));

        !$goods_sku && $this->sys_message->wrong('参数错误!');

        $goods_sku['sku_number'] <= 0 && $this->sys_message->wrong('库存为0!');


        $data = array(
            'sku_id' => $sku_id,
            'storage_number' => $goods_sku['sku_number']
        );

        $order_number_arr = $this->order_goods_model->allot_pg_number($data);

        if ($order_number_arr['occupy_number'] > 0) {

            foreach ($order_number_arr['rec_ids'] as $rec_id => $row) {
                $log_info = "<br /> #{$rec_id} 订单产品占用 <b style='color: #ab2134'>{$row['need_number']}</b> 个库存";

                $purchase = $this->purchase_goods_model->subtract_order_purchase_number($rec_id, $row['need_number']);
                $log_info .= $purchase ? "<br /> 取消 #{$purchase['pg_id']} 采购产品 <b style='color: #ab2134'>{$purchase['number']}</b> 个采购"  : '';

                $this->order_model->check_orders($row['order_id'], 2, $log_info);
            }

            $this->goods_sku_model->take_sku($data['sku_id'], 2, 0, $order_number_arr['occupy_number'], "库存重新分配至订单");

            $this->sys_message->success('成功!');
        } else {
            $this->sys_message->warning('没有需要分配的订单!');
        }

    }
    //下架列表
    public function lower_shelf(){
        //echo date('Y-m-d H:i');die;
        $this->load->library('eccang');
        $this->load->library('pagination');
        $assoc = $this->uri->uri_to_assoc();
        $this->load->model('goods_sku_model');
        $this->load->model('suppliers_model');
        $supp = $this->suppliers_model->suppliers_option();
        $_param_option = array(
            'lower' => array(
                'col' => 'col-lg-1',
                'type' => 'option',
                'placeholder' => '新老品筛选',
                'option' => array(
                    1 => '新品',
                    2 => '老品'
                )
            ),
            'supp_id' => array(
                'col' => 'col-lg-1',
                'type' => 'option',
                'placeholder' => '选择供应商',
                'option' => $supp,
            ),
            'add_time' => array(
                'col' => 'col-lg-4',
                'type' => 'dpd_time',
                'placeholder' => '时间'
            )
        );

        //echo date('Y-m-d H:i:s');die;

            // $res['dateFor'] = '2019-06-22 00:00:00';
            // $res['dateTo'] = '2019-06-23 00:00:00';
            // $res['pageSize'] = 1000;
            // $res['page'] = 1;
            // $res['searchDateType'] = 'createDate';
            // // $res['supplier'] = [477];
            // // $res['supplier'] = json_encode(477);
            // $e_res = $this->eccang->same_list_sku($res);
            // print_R($e_res);die;

        $_param = array(
            'lower' => $this->input->get('lower'),
            'supp_id' => $this->input->get('supp_id'),
            'page' => $assoc['page'] > 0 ? intval($assoc['page']) - 1 : 0,
            'add_time_start' => trim($this->input->get('add_time_start')),
            'add_time_end' => trim($this->input->get('add_time_end')),
        );
        $config['base_url'] = base_url('GoodsSku/') . 'lower_shelf/page/';
        $config['total_rows'] = $this->goods_sku_model->lower_shelf_sku_num($_param);
        $config['num_links'] = 6;
        $config['per_page'] = $this->goods_sku_model->limit_rows;
        $config['use_page_numbers']=true;
        // print_R($config);die;
        $this->pagination->initialize($config);
        $lower_shelf_sku = $this->goods_sku_model->lower_shelf_sku($_param);
        // //E仓当天采购数量
        // $arr = [];
        // if($_param['supp_id'] > 0){
        //     $e_code = $this->db->from('suppliers')->select('e_code')->where(['suppliers_id'=>$_param['supp_id']])->get()->row_array();
        //     // $res['supplier']   = json_encode($e_code['e_code']);
        //     // $res['supplier']   = (Object)$e_code['e_code'];
        //     // $res['supplier']   = '['.$e_code['e_code'].']';
        //     // print_R($e_code['e_code']);die;
        // }
        // //没选时间默认今天
        // if($_param['add_time_start'] && $_param['add_time_end']){
        //     $res['dateFor'] = date('Y-m-d H:i:s',strtotime($_param['add_time_start']));
        //     $res['dateTo']   = date('Y-m-d H:i:s',strtotime($_param['add_time_end']));
        // }else{
        //     $res['dateFor'] = date('Y-m-d');
        //     $res['dateTo']   = date('Y-m-d H:i:s',strtotime(date('Y-m-d')) + 86400);
        // }
        

        // for ($i=1; $i <20 ; $i++) {
        //     $res['pageSize']  = '100';
        //     $res['page']  = $i;
        //     $res['searchDateType'] = 'createDate';
        //     $e_res = $this->eccang->same_list_sku($res);
        //     if(empty($e_res['data'])){
        //         break;
        //     }
        //     foreach ($e_res['data'] as $key => $value) {
        //         $arr = array_merge($arr,$value['detail']);
        //     }
        // }
        // // print_R($arr);die;
        // //当天下架总数
        // $counts = $this->goods_sku_model->lowershelf($_param);




        //print_R($lower_shelf_sku);die;
        $data = array(
            'lower_shelf_sku' => $lower_shelf_sku,
            'pages' => $this->pagination->create_links(),
            'param_option' => $_param_option,
            'param' => $_param,
            // 'count' => count($arr),
            // 'counts' => $counts['count']
        );

        $this->load->view('lower_shelf',$data);
    }

    public function ajax_e_count(){
        $start = $this->input->post('start');
        $end = $this->input->post('end');
        if($start && $end){
            $start = strtotime($start);
            $end   = strtotime($end);
        }else{
            $start = strtotime(date('Y-m-d'));
            $end   = strtotime(date('Y-m-d')) + 86400;
        }

        //e仓SKU
        $res = $this->db->from('purchase_goods_e pg')
            ->select('count(*) as count')
            ->join('purchase_order_e po','po.id = pg.po_id','left')
            ->where("po.date_create between $start and $end")
            ->get()
            ->row_array();
        $this->load->model('goods_sku_model');
        //当天下架总数
        $counts = $this->goods_sku_model->lowershelf($start,$end);

        if($res['count'] == 0){
            echo '0 = '. $counts['count'] .' / '. $res['count'];die;
        }else{
            echo $counts['count'] / $res['count'] .' = '. $counts['count'] .' / '. $res['count'];die;
        }
    }

    public function getProductInventorys(){
        $data['pageSize'] = 500;
        $data['page'] = $this->input->get('page');
        $this->load->library('eccang');
        $res = $this->eccang->getProductInventorys($data);
        if(empty($res['data'])){
            echo 1;die;
        }
        foreach ($res['data'] as $k => $v) {
            if($v['Sellable'] != 0){
                $this->db->where(['sku_sn'=>$v['productSku']])->update('goods_sku',['sku_number'=>$v['Sellable']]);
            }
        }
    }



    public function goods_id_array(){
        $goods_id_select = $this->db->from('goods_sku')
            ->select('goods_id')
            ->where_in('sku_sn',$sku_sn)
            ->group_by('goods_id')
            ->get()->result_array();
            foreach ($goods_id_select as $k => $v) {
                $goods_aa[] = $v['goods_id'];
            }
        print_r($goods_aa);die;
    }

    public function shopify_goods_xin(){
        $this->load->model('siteweb_model');
        $this->load->model('goods_model');
        $this->load->model('shopify_goods_model');
        $this->load->model('goods_sku_model');
        $this->load->library('sys_message');
        $this->load->model('tagslist_model');
        
        $web_id = 24;
        $siteweb = $this->siteweb_model->siteweb_info(array('web_id' => $web_id));

        $goods_1 = array('4295','4304','3055','2855','2496','3225');


        // switch ($page) {
        //     case 2:
        //         $goods_1 = array('1430','1436','1437','1439','1446','1452','1454','1455','1457','1458');
        //         break;
        // }
        foreach ($goods_1 as $key => $goods_id) {

            $goods = $this->goods_model->goods_info($goods_id);
            $goods_sku = $this->db->from('goods_sku')->where(['goods_id'=>$goods_id])->get()->result_array();
            
            foreach ($goods_sku as $k_sku => $v_sku) {
                if($v_sku['sku_number'] == 0){
                    unset($goods_sku[$k_sku]);
                }
            }
            $variants = array();
            foreach ($goods_sku as $row) {
                $variants[] = array(
                    'option1' => $row['size'],
                    'option2' => $row['color'],
                    'sku' => $siteweb['ab_name'] . $row['sku_num_sn'],
                    'price' => $goods['shop_price'],
                    'inventory_quantity' => $row['sku_number'],
                    "fulfillment_service" => "manual",
                    'inventory_management' => 'shopify'
                );
            }
            
            $data = array(
                'goods_id' => $goods['goods_id'],
                'goods_sn' => $siteweb['ab_name'] . preg_replace("/[a-zA-Z]/","",$goods['goods_sn']),
                'web_id' => $web_id,
                'goods_name' => "{$siteweb['title']} " . $goods['goods_name'],
                'cat_id' => $goods['cat_id'],
                'shop_price' => $goods['shop_price'],
                'market_price' => $goods['market_price'],
                'body_html' => $goods['body_html'],
                'is_sales' => 1,
                'variants' => $variants,
                'tags' => $this->tagslist_model->tags_in($goods['tags'])
            );

            $goods['goods_attr'] = json_decode($goods['goods_attr'], true);

            if ($goods['goods_attr'] && count($goods['goods_attr']['attr_val']) > 1) {
                $html = '<table><tr>';
                foreach ($goods['goods_attr']['attr_title'] as $attr_title) {
                    $html .= '<td>' . $attr_title . '</td>';
                }
                $html .= '</tr>';

                $_attr = array();
                foreach ($goods['goods_attr']['attr_val'] as $k => $_row) {
                    foreach ($_row as $_k => $_row_attr) {
                        $_attr[$_k][$k] = $_row_attr;
                    }
                }

                foreach ($_attr as $k_val => $_attr_val) {
                    $html .= '<tr>';
                    foreach ($_attr_val as $k_title => $attr_title) {
                        if ($k_title == 0) {
                            $html .= '<td>' . $attr_title . '</td>';
                        } else {
                            $attr_val = explode('-', $attr_title);

                            $a1 = sprintf('%.1f', $attr_val[0] / 2.54);
                            $a2 = $attr_val[1] ? ("-" . sprintf('%.1f', $attr_val[1] / 2.54)) : '';
                            $html .= '<td>' . $a1 . $a2 . '(' . $attr_title . 'cm)' . '</td>';
                        }
                    }
                    $html .= '</tr>';
                }
                $html .= '</table>';
                $data['body_html'] .= $html;
            }
            // print_R($data);die;
            $sg_id = $this->shopify_goods_model->insert_goods($data);

            if ($sg_id) {
                //商品图片
                $shopify_data = $this->shopify_goods_model->up_shopify_data($sg_id);
                // print_r($shopify_data);die;
                $this->load->library('shopify_api', $siteweb);

                $response = $this->shopify_api->upload_goods($shopify_data);
    
                if ($response) {

                    $shopify_goods_data = array(
                        'shopify_id' => $response['id'],
                        'update_time' => 0
                    );
                    $this->shopify_goods_model->update_goods($sg_id, $shopify_goods_data);
                }

            }
        }
        echo 1;die;
    }
}